package cn.edu.ldu.views.modules.oss;

import cn.edu.ldu.views.ServerView;

import javax.swing.*;
import java.io.*;
import java.net.Socket;

public class ReceiveFile extends SwingWorker<Integer, Object> {

    private final Socket fileSocket;
    private ServerView parentView;
    private static final int BUF_SIZE = 8096;

    public ReceiveFile(Socket fileSocket, ServerView parentView){
        this.fileSocket = fileSocket;
        this.parentView = parentView;
    }


    @Override
    protected Integer doInBackground() throws Exception {
        //获取套接字输入流
        DataInputStream in = new DataInputStream(new BufferedInputStream(fileSocket.getInputStream()));
        //接收文件名、文件长度
        String fileName = in.readUTF();
        int fileLen = (int)in.readLong();
        //创建文件输入流
        File file = new File("./upload/" + fileName);
        //创建文件输出流
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        //接收文件内容，存储为外部文件
        byte[] buffer = new byte[BUF_SIZE];      //读入缓冲区
        int numRead = 0;                         //单次读取的字节数
        int numFinished = 0;                     //完成字节数
        while (numFinished < fileLen && (numRead = in.read(buffer)) != -1){     //输入流可读
            out.write(buffer, 0, numRead);
            numFinished += numRead;     //已完成字节数
        }
        //定义字符输出流
        PrintWriter pw = new PrintWriter(fileSocket.getOutputStream(), true);
        if(numFinished >= fileLen){     //文件接收完成
            pw.println("M_DONE");       //回送成功消息
            parentView.consoleJTA(fileName + "接收成功！\n");
        }else {
            pw.println("M_LOST");       //回送失败消息
            parentView.consoleJTA(fileName + "接收失败！\n");
        }
        in.close();
        out.close();
        pw.close();
        fileSocket.close();
        return 100;
    }
}
